//   Copyright 2012,2013 Vaughn Vernon
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.
package com.saasovation.common.port.adapter.persistence.hibernate;

import com.saasovation.common.domain.model.process.ProcessId;
import com.saasovation.common.domain.model.process.TimeConstrainedProcessTracker;
import com.saasovation.common.domain.model.process.TimeConstrainedProcessTrackerRepository;
import org.hibernate.SessionFactory;
import org.hibernate.exception.ConstraintViolationException;
import org.hibernate.query.Query;

import java.util.Collection;
import java.util.Date;

public class HibernateTimeConstrainedProcessTrackerRepository
        implements TimeConstrainedProcessTrackerRepository {
    private final SessionFactory sessionFactory;

    public HibernateTimeConstrainedProcessTrackerRepository(SessionFactory sessionFactory) {
        super();
        this.sessionFactory = sessionFactory;
    }

    @Override
    public void add(TimeConstrainedProcessTracker aTimeConstrainedProcessTracker) {
        this.save(aTimeConstrainedProcessTracker);
    }

    @Override
    public Collection<TimeConstrainedProcessTracker> allTimedOut() {
        Query<TimeConstrainedProcessTracker> query = this.sessionFactory.getCurrentSession()
                .createQuery("from com.saasovation.common.domain.model.process.TimeConstrainedProcessTracker as tcpt "
                                + "where tcpt.completed = false and"
                                + " tcpt.processInformedOfTimeout = false and"
                                + " tcpt.timeoutOccursOn <= :occursOn",
                        TimeConstrainedProcessTracker.class);
        query.setParameter("occursOn", (new Date()).getTime());
        return query.list();
    }

    @Override
    public Collection<TimeConstrainedProcessTracker> allTimedOutOf(String aTenantId) {
        Query<TimeConstrainedProcessTracker> query = this.sessionFactory.getCurrentSession()
                .createQuery("from com.saasovation.common.domain.model.process.TimeConstrainedProcessTracker as tcpt "
                                + "where tcpt.tenantId = :tenantId "
                                + "and tcpt.completed = false "
                                + "and tcpt.processInformedOfTimeout = false "
                                + "and tcpt.timeoutOccursOn <= :occursOn",
                        TimeConstrainedProcessTracker.class);
        query.setParameter("tenantId", aTenantId);
        query.setParameter("occursOn", (new Date()).getTime());
        return query.list();
    }

    @Override
    public Collection<TimeConstrainedProcessTracker> allTrackers(String aTenantId) {
        Query<TimeConstrainedProcessTracker> query = this.sessionFactory.getCurrentSession().
                createQuery("from com.saasovation.common.domain.model.process.TimeConstrainedProcessTracker as tcpt " +
                                "where tcpt.tenantId = :tenantId",
                        TimeConstrainedProcessTracker.class);
        query.setParameter("tenantId", aTenantId);
        return query.list();
    }

    @Override
    public void save(TimeConstrainedProcessTracker aTimeConstrainedProcessTracker) {
        try {
            this.sessionFactory.getCurrentSession().persist(aTimeConstrainedProcessTracker);
        } catch (ConstraintViolationException e) {
            throw new IllegalStateException("Either TimeConstrainedProcessTracker is not unique " +
                    "or another constraint has been violated.", e);
        }
    }

    @Override
    public TimeConstrainedProcessTracker trackerOfProcessId(String aTenantId, ProcessId aProcessId) {
        Query<TimeConstrainedProcessTracker> query = this.sessionFactory.getCurrentSession()
                .createQuery("from com.saasovation.common.domain.model.process.TimeConstrainedProcessTracker as tcpt "
                                + "where tcpt.tenantId = :tenantId and tcpt.processId = :processId",
                        TimeConstrainedProcessTracker.class);
        query.setParameter("tenantId", aTenantId);
        query.setParameter("processId", aProcessId);
        return query.uniqueResult();
    }

}
